<?php

namespace app\admin\controller\shops;

use app\common\controller\Backend;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use app\common\model\Config;
use app\admin\model\Middleman;
use app\admin\model\ShopFollow;
use app\admin\model\ShopPlatform;
use app\admin\model\Admin;
use app\admin\model\Play;
use think\Loader;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;

/**
 * 店铺管理
 *
 */
class Shop extends Backend
{

    /**
     * Shop模型对象
     * @var \app\admin\model\Shop
     */
    protected $noNeedRight = ['isShopRepeat','autocomplete'];
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Shop;
        $this->view->assign("shopTypeList", $this->model->getShopTypeList());
        $this->view->assign("statusList", $this->model->getShopStatusList());
        $this->view->assign("shopCategory", $this->model->getCategoryNoList());
        // $this->db2 = Db::connect(config('database.db2'));
        // 分发渠道
        $this->channel = Db::name('channel')->where(['status'=>1])->select();
        $this->view->assign("channel", $this->channel);
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */



    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $start_date = strtotime(date('Y-m-d'));
            $end_date = $start_date+86399;
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $filter = input('filter','');
            $decode = json_decode($filter,1);
            $uploaddomain = config('upload_domain');
            if (isset($decode['submission_channel']) && !isset($decode['limited_user'])) {
                $where2 = '1=1';
                if (isset($decode['id'])) {
                    $where2 .= ' and shop.id='.$decode['id'];
                }
                if (isset($decode['shop_name'])) {
                    $where2 .= ' and shop.shop_name like "%'.$decode['shop_name'].'%"';
                }
                if (isset($decode['shop_type'])) {
                    $where2 .= ' and shop.shop_type='.$decode['shop_type'];
                }
                if (isset($decode['is_auth'])) {
                    $where2 .= ' and shop.is_auth='.$decode['is_auth'];
                }
                if (isset($decode['admin.nickname'])) {
                    $where2 .= ' and admin.nickname like "%'.$decode['admin.nickname'].'%"';
                }
                if (isset($decode['contact_user'])) {
                    $where2 .= ' and shop.contact_user like "%'.$decode['contact_user'].'%"';
                }
                if (isset($decode['phone'])) {
                    $where2 .= ' and shop.phone like "%'.$decode['phone'].'%"';
                }
                if (isset($decode['address'])) {
                    $where2 .= ' and shop.address like "%'.$decode['address'].'%"';
                }
                if (isset($decode['shop_status'])) {
                    $where2 .= ' and shop_status='.$decode['shop_status'];
                } else {
                    $where2 .= ' and shop_status=1';
                }
                // 店铺在线
                if ($decode['submission_channel']==5) {
                    $where2 .= ' and play.place_time>='.$start_date.' and play.place_time<='.$end_date;
                    $list = Db::name('shop')->alias('shop')
                            ->field('shop.*,admin.nickname as anickname')
                            ->join('chbc_play_order play','shop.shop_no=play.shop_no','left')
                            ->join('chbc_admin admin','shop.salesman_admin_id=admin.id','left')
                            ->where($where2)
                            ->group('shop.shop_no')
                            // ->where('shop_status',1)
                            ->order($sort, $order)
                            ->paginate($limit);
                    $list2 = $list->items();
                    foreach ($list2 as &$row) {
                        $row['logo_pic'] = $uploaddomain.$row['logo_pic'];
                        $row['have_uid'] = $row['have_uid']>0?1:0;
                        $admin = ['nickname'=>$row['anickname']];
                        $row['admin'] = $admin;
                        $row['category_no_text'] = $this->model->getCategoryNoTextAttr($row['category_no'],$row);
                        $row['submission_channel'] = 5;//店铺在线
                        $row['nopay'] = Db::name('play_order')->where(['shop_no'=>$row['shop_no'],'order_status'=>['in',[3,6,-9]],'is_pay'=>0])->value('sum(actual_rebate_amt+service_charge_amt)');
                    }

                    $result = array("total" => $list->total(), "rows" => $list2);

                    return json($result);
                // 店铺不在线
                } elseif ($decode['submission_channel']==6) {
                    $sqls = 'from (SELECT count(play.id) as count,`shop`.`id`,`shop`.`shop_no`,`shop`.`shop_name`,`shop`.`logo_pic`,`shop`.`category_no`,`shop`.`business_time_no`,`shop`.`business_time`,`shop`.`contact_user`,`shop`.`phone`,`shop`.`address`,`shop`.`coordinate`,`shop`.`lng`,`shop`.`lat`,`shop`.`business_license_pic`,`shop`.`have_uid`,`shop`.`submit_by`,`shop`.`approve_by`,`shop`.`approve_time`,`shop`.`reject_content`,`shop`.`shop_status`,`shop`.`create_by`,`shop`.`create_dt`,`shop`.`update_by`,`shop`.`update_dt`,`shop`.`delete_dt`,`shop`.`shop_type`,`shop`.`shop_area`,`shop`.`salesman_admin_id`,`shop`.`middleman_id`,`shop`.`serviceman_admin_id`,`shop`.`submission_channel`,`shop`.`service_amt`,`shop`.`address2`,`shop`.`province`,`shop`.`city`,`shop`.`area`,`shop`.`middleman_id2`,`shop`.`is_sjzp`,`shop`.`is_auth`,admin.nickname as anickname FROM `chbc_shop` `shop` LEFT JOIN `chbc_admin` `admin` ON `shop`.`salesman_admin_id`=`admin`.`id` LEFT JOIN `chbc_play_order` `play` ON `shop`.`shop_no`=`play`.`shop_no` and play.place_time>='.$start_date.' and play.place_time<='.$end_date.' WHERE '.$where2.' GROUP BY `shop`.`shop_no`) a where a.count=0';
                    $sql = 'select * '.$sqls.' ORDER BY a.id DESC LIMIT '.$offset.','.$limit;
                    $list = Db::query($sql);
                    foreach ($list as &$row) {
                        $row['logo_pic'] = $uploaddomain.$row['logo_pic'];
                        $row['submission_channel'] = 6;//店铺不在线
                        
                        $row['admin']['nickname'] = $row['anickname'];
                        $row['category_no_text'] = config('site.shop_category')[$row['category_no']];
                        $row['nopay'] = Db::name('play_order')->where(['shop_no'=>$row['shop_no'],'order_status'=>['in',[3,6,-9]],'is_pay'=>0])->value('sum(actual_rebate_amt+service_charge_amt)');
                    }
                    $sql2 = 'select count(*) as num '.$sqls;
                    $num = Db::query($sql2);
                    $result = array("total" => $num[0]['num'], "rows" => $list);

                    return json($result);
                    
                }
            }
            $where2 = '1=1';
            if (isset($decode['shop_status'])) {
                $where2 .= ' and shop_status='.$decode['shop_status'];
            } else {
                $where2 .= ' and shop_status=1';
            }
            $list = Db::name('shop')->alias('shop')
                    ->field('shop.*,admin.nickname as anickname')
                    // ->join('chbc_user user','shop.have_uid=user.id','left')
                    ->join('chbc_admin admin','shop.salesman_admin_id=admin.id','left')
                    ->where($where)
                    ->where($where2)
                    // ->where('shop_status',1)
                    ->order($sort, $order)
                    ->paginate($limit);
            $list2 = $list->items();
            foreach ($list2 as &$row) {
                $row['logo_pic'] = $uploaddomain.$row['logo_pic'];
                $admin = ['nickname'=>$row['anickname']];
                $row['admin'] = $admin;
                $row['category_no_text'] = $this->model->getCategoryNoTextAttr($row['category_no'],$row);
                // 店铺在线状态
                $play = Db::name('play_order')->where('shop_no='.$row['shop_no'].' and place_time>='.$start_date.' and place_time<='.$end_date)->find();
                if (!$play) {
                    $row['submission_channel'] = 6;//店铺不在线
                } else {
                    $row['submission_channel'] = 5; //店铺在线
                }
                $row['nopay'] = Db::name('play_order')->where(['shop_no'=>$row['shop_no'],'order_status'=>['in',[3,6,-9]],'is_pay'=>0])->value('sum(actual_rebate_amt+service_charge_amt)');
            }

            $result = array("total" => $list->total(), "rows" => $list2);

            return json($result);
        }
        $salesmanList = [];
        $salesman = $this->salesmanList();
        foreach ($salesman as $key => $value) {
            $salesmanList[$value['nickname']] = $value['nickname'];
        }
        $this->assignconfig(['salesmanList' => $salesmanList]);
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }


                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    // 商家是否存在，如果不存在要新增商家
                    $params['phone'] = intval($params['phone']);
                    $user = Db::name('user')->where(['user_type'=>1,'mobile'=>$params['phone']])->find();
                    if ($user && $user['status']!='normal') $this->error('商家账号状态异常');
                    if (!$user) {
                        $insertid = Db::name('user')->insertGetId([
                            'user_type' => 1,
                            'mobile' => $params['phone'],
                            'createtime' => time(),
                            'updatetime' => time(),
                            'status' => 'normal'
                        ]);
                        $params['have_uid'] = $insertid;
                    } else {
                        $params['have_uid'] = $user['id'];
                    }
                    $params['back_money'] = json_encode([1=>$params['back_money'][0],2=>$params['back_money'][1],999999=>$params['back_money'][2]]);
                    //$params['shop_settlement'] = json_encode([1=>$params['shop_settlement'][0],2=>$params['shop_settlement'][1],999999=>$params['shop_settlement'][2]]);
                    $params['shop_name'] = trim($params['shop_name']);
                    $res = $this->isShopRepeat($params['shop_name'],$params['shop_type']);
                    $params['shop_no'] = $this->generateNo(['biz_tag'=>'shop_no','len'=>10,'int_prefix'=>1]);

                    $params['create_by'] = $this->auth->id;
                    if ($params['shop_area']) {
                        $arr = explode('/', $params['shop_area']);
                        if (count($arr)<3) {
                            $this->error('必须选择省市区');
                        }
                        $params['province'] = isset($arr[0])?$arr[0]:'';
                        $params['city'] = isset($arr[1])?$arr[1]:'';
                        $params['area'] = isset($arr[2])?$arr[2]:'';
                    }
                    $params['business_time'] = [];
                    if (isset($params['business_time_start']) && $params['business_time_start'] && isset($params['business_time_end']) && $params['business_time_end']) {
                        $params['business_time'] = [
                            ['start'=>$params['business_time_start'],'end'=>$params['business_time_end']]
                        ];
                    }
                    $params['business_time'] = json_encode($params['business_time']);
                    unset($params['business_time_start']);
                    unset($params['business_time_end']);
                    // 饿了么大牌专享小程序路径
                    if (in_array($params['shop_type'], [2,3])) $params['is_auth']=1;
                    $result = $this->model->allowField(true)->save($params);
                    // 平台信息
                    $create = [
                        'shop_no' => $params['shop_no'],
                        'qrcode_pic' => $params['qrcode_pic'],
                    ];
                    ShopPlatform::create($create);
                    // 跟进业务员
                    ShopFollow::create([
                        'shop_no' => $params['shop_no'],
                        'follow_admin_id' => $params['salesman_admin_id'],
                        'is_head' => 1,
                    ]);
                    
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        // 业务员
        $salesmanList = $this->salesmanList();
        // 客服
        $servicemanList = $this->servicemanList();
        // 中间人
        $group = Db::name('auth_group_access')->where('uid',$this->auth->id)->order('group_id DESC')->value('group_id');
        if ($group==1) {
            $middleman = Middleman::where('no>0 and real_name<>"" and delete_dt is null')->field('id,real_name')->select();  
        } elseif ($group==3) {
            $middleman = Middleman::where('no>0 and real_name<>"" and delete_dt is null and salesman_admin_id='.$this->auth->id)->field('id,real_name')->select();  
        } elseif ($group==5) {
            $admin = Db::name('admin')->where('leader='.$this->auth->id)->value('group_concat(id)');
            $middleman = Middleman::where('no>0 and real_name<>"" and delete_dt is null and salesman_admin_id in ('.$admin.')')->field('id,real_name')->select(); 
        } else {
            $middleman = [];
        }  
        $this->view->assign("middleman", $middleman);
        $this->view->assign("salesmanList", $salesmanList);
        $this->view->assign("servicemanList", $servicemanList);
            return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        $ShopPlatform = ShopPlatform::where('shop_no',$row['shop_no'])->find();
        $ShopFollow = ShopFollow::where(['shop_no'=>$row['shop_no'],'is_head'=>1])->find();
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                // 商家是否存在，如果不存在要新增商家
                $params['phone'] = intval($params['phone']);
                if ($params['phone']!=$row['phone']) {
                    $user = Db::name('user')->where(['user_type'=>1,'mobile'=>$params['phone']])->find();
                    if ($user && $user['status']!='normal') $this->error('商家账号状态异常');
                    if (!$user) {
                        $insertid = Db::name('user')->insertGetId([
                            'user_type' => 1,
                            'mobile' => $params['phone'],
                            'createtime' => time(),
                            'updatetime' => time(),
                            'status' => 'normal'
                        ]);
                        $params['have_uid'] = $insertid;
                    } else {
                        $params['have_uid'] = $user['id'];
                    }
                }
                $params = $this->preExcludeFields($params);
                $params['back_money'] = json_encode([1=>$params['back_money'][0],2=>$params['back_money'][1],999999=>$params['back_money'][2]]);
                //$params['shop_settlement'] = json_encode([1=>$params['shop_settlement'][0],2=>$params['shop_settlement'][1],999999=>$params['shop_settlement'][2]]);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    // $users = Db::name('user')->where('id',$params['have_uid'])->find();
                    // if ($users['user_type']==2) {
                    //     $this->error('非商家身份');
                    // }
                    // if ($users['status']=='hidden') {
                    //     $this->error('商家被禁用');
                    // }
                    $params['update_by'] = $this->auth->id; 
                    if ($params['shop_area']) {
                        $arr = explode('/', $params['shop_area']);
                        if (count($arr)<3) {
                            $this->error('必须选择省市区');
                        }
                        $params['province'] = isset($arr[0])?$arr[0]:'';
                        $params['city'] = isset($arr[1])?$arr[1]:'';
                        $params['area'] = isset($arr[2])?$arr[2]:'';
                    }
                    $params['business_time'] = [];
                    if (isset($params['business_time_start']) && $params['business_time_start'] && isset($params['business_time_end']) && $params['business_time_end']) {
                        $params['business_time'] = [
                            ['start'=>$params['business_time_start'],'end'=>$params['business_time_end']]
                        ];
                    }
                    $params['business_time'] = json_encode($params['business_time']);
                    unset($params['business_time_start']);
                    unset($params['business_time_end']);
                    // 饿了么大牌专享小程序路径
                    if ($params['shop_type']==1) $params['dpzxelm']=0;
                    $result = $row->allowField(true)->save($params);
                    // 平台信息
                    $create = [
                        'shop_no' => $row['shop_no'],
                        'qrcode_pic' => $params['qrcode_pic'],
                    ];
                    if ($ShopPlatform) {
                        $ShopPlatform->save($create);
                    } else {
                        $ShopPlatform = new ShopPlatform();
                        $ShopPlatform->save($create);
                    }

                    // 跟进业务员
                    if (!isset($ShopFollow['follow_admin_id']) || $ShopFollow['follow_admin_id']!=$params['salesman_admin_id']) {
                        if (isset($ShopFollow['follow_admin_id'])) {
                            $ShopFollow->save(['is_head'=>0]);
                        }
                        ShopFollow::create([
                            'shop_no' => $row['shop_no'],
                            'follow_admin_id' => $params['salesman_admin_id'],
                            'is_head' => 1,
                        ]);
                    }
                    
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $rows = $row;
        $rows['platform_no'] = $ShopPlatform['platform_no'];
        $rows['qrcode_pic'] = $ShopPlatform['qrcode_pic'];
        $rows['is_xls'] = $ShopPlatform['is_xls'];
        $rows['elm_appenter'] = $ShopPlatform['elm_appenter'];
        $back_money_arr = json_decode($rows['back_money'],1);
        // $shop_settlement_arr = json_decode($rows['shop_settlement'],1);
        $rows['back_money'] = $back_money_arr;
        // $rows['shop_settlement'] = $shop_settlement_arr;
        // 业务员
        $salesmanList = $this->salesmanList();
        // 客服
        $servicemanList = $this->servicemanList();
        // 中间人
        $group = Db::name('auth_group_access')->where('uid',$this->auth->id)->order('group_id DESC')->value('group_id');
        if ($group==1) {
            $middleman = Middleman::where('no>0 and real_name<>"" and delete_dt is null')->field('id,real_name')->select();  
        } elseif ($group==3) {
            $middleman = Middleman::where('no>0 and real_name<>"" and delete_dt is null and salesman_admin_id='.$this->auth->id)->field('id,real_name')->select();  
        } elseif ($group==5) {
            $admin = Db::name('admin')->where('leader='.$this->auth->id)->value('group_concat(id)');
            $middleman = Middleman::where('no>0 and real_name<>"" and delete_dt is null and salesman_admin_id in ('.$admin.')')->field('id,real_name')->select(); 
        } else {
            $middleman = [];
        }
        // shop_serviceamt
        $shop_serviceamt = Db::name('shop_serviceamt')->where(['shop_no'=>$row['shop_no'],'status'=>1])->select();
        $channel = [];
        if ($shop_serviceamt) {
            $storage = [];
            foreach ($shop_serviceamt as $key => $value) {
                $channel = Db::name('channel')->where('id',$value['channel_id'])->field('id,status,name')->find();
                $storage[] = $channel['name'];
                if ($channel['status']==0) {
                    Db::name('shop_serviceamt')->where(['id'=>$value['id']])->update(['status'=>0]);
                    unset($shop_serviceamt[$key]);continue;
                }
            }
            foreach ($this->channel as $k => $v) {
                if (!in_array($v['name'], $storage)) {
                    $shop_serviceamt[] = ['channel_name'=>$v['name'],'service_amt'=>0];
                }
            }
        } else {
            $shop_serviceamt=[];
            $channel = Db::name('channel')->where('status',1)->field('id,status,name')->select();
            foreach ($channel as $key => $value) {
                $shop_serviceamt[$key] = ['channel_name'=>$value['name'],'service_amt'=>0];
            }
        }
        // $business_time = json_decode($rows['business_time'],1);
        // $business_time_start = $business_time[0]['start'];
        // $business_time_end = $business_time[0]['end'];
        // $this->view->assign("business_time_start", $business_time_start);
        // $this->view->assign("business_time_end", $business_time_end);
        $this->view->assign("middleman", $middleman);
        $this->view->assign("salesmanList", $salesmanList);
        $this->view->assign("servicemanList", $servicemanList);
        $this->view->assign("shop_serviceamt", $shop_serviceamt);
        $this->view->assign("row", $rows);
        return $this->view->fetch();
    }


    public function bill($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $url = config('bill_domain') . '/?bill='.$row['shop_no'];
        $qrcode = $this->billQrcode($row['shop_no'],2,$url);
        // 改成商家关联的店铺
        $shops = Db::name('user')->alias('u')->join('chbc_shop s','s.shop_no=u.shop_no')->field('s.*')->where(['u.id'=>$row['have_uid']])->find();
        if (!$shops) $shops = $row;
        $this->view->assign("shops", $shops);
        $this->view->assign("row", $row);
        $this->view->assign("qrcode", $qrcode);
        $this->view->assign("url", $url);
        return $this->view->fetch();
    }

    /**
     * 添加活动
     */
    public function addplay($ids = nill)
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                // 分发渠道
                if (!isset($params['channel_id']) || !isset($params['quota'])) {
                    $this->error('请填写分发渠道信息');
                }
                if (count($params['channel_id'])!=count($params['quota'])) {
                    $this->error('分发渠道信息有误');
                }
                $channel = [];
                $quota = 0;
                foreach ($params['channel_id'] as $key => $value) {
                    if ($value=='吃喝不愁' && $params['quota'][$key]==0) $this->error($value.'渠道名额不能为0');
                    $channel[$key]['channel_id'] = Db::name('channel')->where('name',$value)->value('id');
                    if (!$channel[$key]['channel_id']) $this->error('未查询到渠道信息');
                    $channel[$key]['channel_name'] = $value;
                    $channel[$key]['quota'] = $params['quota'][$key];
                    $quota += $params['quota'][$key];
                    $channel[$key]['channel_status'] = $params['channel_status'][$key];
                    if ($channel[$key]['channel_name']=='吃喝不愁') {
                        $params['chbcquota'] = $channel[$key]['quota'];
                    }
                }
                if ($quota!=$params['num']) {
                    $this->error('分发总名额有误');
                }
                $params['channel'] = json_encode($channel,JSON_UNESCAPED_UNICODE);
                unset($params['channel_id']);
                unset($params['quota']);
                unset($params['channel_status']);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                if (!isset($params['shop_no']) || !$params['shop_no']) $this->error('请选择正确的店铺');
                $shop = (new \app\admin\model\Shop())->where(['shop_no' => $params['shop_no'], 'shop_status' => 1])->find();
                if (empty($shop)) $this->error('该店铺暂不能发布活动');
                // $user = (new \app\common\model\User())->where(['id' => $shop['have_uid'], 'user_type' => '1','status'=>'normal'])->find();
                // if (empty($user)) $this->error('商家被封禁');
                if ($params['num'] <= 0) $this->error('活动名额有误');
                if ($params['play_type']==2 && !isset($params['is_qcsc'])) {
                    $this->error('请选择返利餐的显示位置');
                }
                if ($params['play_type']==2 && $params['user_pay']!=0) {
                    $this->error('返利餐用户实付金额为0');
                }
                if (!isset($params['date_range']) || !$params['date_range']) $this->error('请选择日期范围');
                $date_range = explode(' - ', $params['date_range']);
                if (count($date_range)!=2) $this->error('日期范围有误');
                $params['start_date'] = strtotime($date_range[0]);
                $params['end_date'] = strtotime($date_range[1]);
                $params['user_id'] = $shop['have_uid'];
                if (strtotime($params['start_time_str']) >= strtotime($params['end_time_str'])) $this->error('请选择正确的活动时间');
                $params['img'] = $shop['logo_pic'];
                $params['shop_name'] = $shop['shop_name'];
                $params['shop_type'] = $shop['shop_type'];
                $params['service_amt'] = $shop['service_amt'];
                $params['stock'] = $params['num'];
                if ($params['shop_settlement'] <= $shop['service_amt']) $this->error('请正确填写结算金额和技术服务费');
                $totalMoney = bcmul($params['user_pay'], $params['num'],2);
                $totalProcess = bcmul($shop['service_amt'], $params['num'],2);
                $params['total_pay'] = $totalMoney;
                $params['total_service_amt'] = $totalProcess;
                $params['back_money'] = bcsub($params['shop_settlement'], $shop['service_amt'],2);
                $params['total_money'] = bcadd(bcmul($params['back_money'], $params['num'],2), $totalProcess,2);
                $params['acture_total_money'] = $params['total_money'];
                $params['play_no'] = $this->generateNo(['biz_tag'=>'play_no','len'=>12,'int_prefix'=>2]);
                if ((isset($params['is_loop']) && $params['is_loop']) || $params['end_date']-$params['start_date']>86400) {
                    $params['super_play_no'] = $this->generateNo(['biz_tag'=>'super_play_no','len'=>12,'int_prefix'=>3]);
                }
                $params['service_admin_id'] = $shop['salesman_admin_id'];
                $params['service_admin_by'] = strval(Admin::where('id',$shop['salesman_admin_id'])->value('nickname'));
                $params['create_by'] = $this->auth->nickname;
                $params['submit_admin_id'] = $this->auth->id;
                $params['play_status'] = 2;  // 后台添加的活动不用审核
                if ($params['play_label']>0) {
                    $params['virtual_num'] = mt_rand(0,5);
                }
                if (isset($params['is_qcsc']) && $params['is_qcsc']==1 && $params['play_type']==2) {
                    $params['play_type']=3;
                }
                $result = false;
                Db::startTrans();
                try {
                    $model = new Play();
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $model->validateFailException(true)->validate($validate);
                    }
                    $result = $model->allowField(true)->save($params);
                    // 立即新建一个当日的普通活动
                    if (isset($params['super_play_no']) && $params['super_play_no'] && time()>$params['start_date']) {
                        $params['parent_play_no'] = $params['super_play_no'];
                        unset($params['super_play_no']);
                        $params['play_no'] = $this->generateNo(['biz_tag'=>'play_no','len'=>12,'int_prefix'=>2]);
                        $time = time();
                        $today_start = strtotime(date('Ymd',$time));
                        $today_end = strtotime(date('Ymd',$time))+86399;
                        $params['start_date'] = $today_start;
                        $params['end_date'] = $today_end;
                        $model = new \app\admin\model\Play;
                        $result = $model->allowField(true)->save($params);
                    }
                    // 渠道
                    foreach ($channel as &$channels) {
                        $channels['play_id'] = $model->id;
                        unset($channels['channel_name']);
                        unset($channels['channel_status']);
                    }
                    Db::name('play_channel')->insertAll($channel);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success('成功','/hFtNsJROTk.php/shops/play?ref=addtabs');
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $where['shop_status'] = ['=',1];
        $where['delete_dt'] = ['null',''];
        $shop = Db::name('shop')->where($where)->field('id,shop_no,shop_name,shop_type')->select();
        foreach ($shop as $key => &$value) {
            $value['shop_name'] = '【'.config('platform')[$value['shop_type']].'】'.$value['shop_name'];
        }
        // $one = Db::name('shop')->where('id',$ids)->field('business_time,shop_no,shop_status')->find();
        // if ($one['shop_status']!=1) {
        //     $this->error(__('No Results were found'));
        // }
        // if (!$one) {
        //     $one = [];
        // } else {
        //     $business_time = json_decode($one['business_time'],1);
        //     $one['startstr'] = $business_time[0]['start'];
        //     $one['endstr'] = $business_time[0]['end'];
        // }
        // $this->view->assign("one", $one);
        $this->view->assign("ids", $ids);
        $this->view->assign("shop", $shop);
        $nopay = Db::name('play_order')->where(['id'=>$ids,'order_status'=>['in',[3,6,-9]],'is_pay'=>0])->value('sum(actual_rebate_amt+service_charge_amt)');
        $shops = Db::name('shop')->where('id',$ids)->find();
        $business_time = json_decode($shops['business_time'],1);
        // 店铺服务费
        $shop_serviceamt = Db::name('shop_serviceamt')->where(['shop_no'=>$shops['shop_no'],'status'=>1])->select();
        $data = [
            'nopay' => (float)$nopay,
            'address' => $shops['address'],
            'shop_type' => config('platform')[$shops['shop_type']],
            'qrcode' => Db::name('shop_platform')->where('shop_no',$shops['shop_no'])->value('qrcode_pic'),
            'domain' => config('upload_domain'),
            'shop_name' => '【'.config('platform')[$shops['shop_type']].'】'.$shops['shop_name'],
            'startstr' => $business_time[0]['start'],
            'endstr' => $business_time[0]['end'],
            'service_amt' => $shops['service_amt'],
            'shop_serviceamt' => json_encode($shop_serviceamt,JSON_UNESCAPED_UNICODE),
        ];
        $this->view->assign("data", $data);
        // 分发渠道
        $channel = Db::name('channel')->where(['status'=>1])->select();
        foreach ($channel as $key => &$value) {
            $value['firstRelease'] = Db::name('play')->where('channel like "%'.$value['name'].'%" and shop_no='.$shops['shop_no'])->count();
        }
        $this->view->assign("channel", $channel);
        return $this->view->fetch();
    }

    /**
     * 复制最后一次活动
     */
    public function copy($ids = null)
    {
        $shop = $this->model->get($ids);
        if (!$shop) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($shop[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        //用户端
        // $url1 = config('h5_domain').'/#/?id='.$shop['shop_no'];
        // $qrcode1 = $this->billQrcode($shop['shop_no'],1,$url1);
        //商家端
        $url2 = config('h5_domain').'/#/?shop_no='.$shop['shop_no'];
        $qrcode2 = $this->billQrcode($shop['shop_no'],3,$url2);
        $this->view->assign("shop", $shop);
        // $this->view->assign("url1", $url1);
        // $this->view->assign("qrcode1", $qrcode1);
        $this->view->assign("url2", $url2);
        $this->view->assign("qrcode2", $qrcode2);
        return $this->view->fetch();
    }

    /**
     * 账单二维码
     */
    public function billQrcode($shop_no,$type,$url)
    {
        if (!$shop_no) {
            return false;
        }
        // 用户端二维码
        $poster = Db::name('share_image')->where([
            'shop_no' => $shop_no,
            'type' => $type//1-用户端二维码2-账单二维码3-商家端二维码    
        ])->find();
        if ($poster && !empty($poster['qrcode'])) {
            return config('domain').$poster['qrcode'];
        } else {
            $config = get_addon_config('qrcode');
            $params = array_intersect_key($config, array_flip(['text', 'size', 'padding', 'errorlevel', 'foreground', 'background', 'logo', 'logosize', 'logopath', 'label', 'labelfontsize', 'labelalignment']));
            $params['text'] = $url;
            $params['label'] = $this->request->get('label', $config['label'], 'trim');

            $qrCode = \addons\qrcode\library\Service::qrcode($params);

            $mimetype = $config['format'] == 'png' ? 'image/png' : 'image/svg+xml';

            // 写入到文件
            if ($config['writefile']) {
                $dirPath = '/uploads/billqrcode/'.date('Ymd').'/';
                $qrcodePath = ROOT_PATH . '/public' . $dirPath;
                if (!is_dir($qrcodePath)) {
                    @mkdir($qrcodePath);
                }
                if (is_really_writable($qrcodePath)) {
                    $imgName = md5(implode('', $params)) . '.' . $config['format'];
                    $filePath = $qrcodePath . $imgName;
                    $qrCode->writeFile($filePath);
                    $data = [
                        'shop_no' => $shop_no,
                        'qrcode' => $dirPath . $imgName,
                        'type' => $type
                    ];
                    $result = Db::name('share_image')->insertGetId($data);
                    return config('domain').$dirPath . $imgName;
                }
            }
        }
        return false;
    }

    /**
     * 店铺是否重复
     * @DateTime 2023-06-01T10:37:18+0800
     * @return   boolean                  [description]
     */
    public function isShopRepeat($shop_name,$shop_type,$id=0)
    {
        // var_dump($shop_name,$shop_type);exit;
        // $shop_name = input('shop_name');
        // $shop_type = input('shop_type');
        if ($id) {
            $shop = Db::name('shop')->where(['shop_name'=>$shop_name,'shop_type'=>$shop_type,'id'=>['<>',$id]])->count();
        } else {
            $shop = Db::name('shop')->where(['shop_name'=>$shop_name,'shop_type'=>$shop_type])->count();
        }
        if ($shop) {
            $this->error('已存在同名店铺');
        }
    }


    public function autocomplete()
    {
        $query = input('query','');
        $data = [];
        $shop = Db::name('shop')->field('shop_name,shop_type')->where('shop_name like "'.$query.'%"')->limit(0,10)->select();
        if ($shop) {
            foreach ($shop as $key => $value) {
                $shop_type = config('platform')[$value['shop_type']];
                $text = $value['shop_name'].'('.$shop_type.')';
                $data[] = $text;
            }
        }
        $res = ['query'=>$query,'suggestions'=>$data];
        echo json_encode($res);exit;
    }

    /**
     * 生成查询所需要的条件,排序方式
     * @param mixed   $searchfields   快速查询的字段
     * @param boolean $relationSearch 是否关联查询
     * @return array
     */
    protected function buildparams($searchfields = null, $relationSearch = null)
    {
        $searchfields = is_null($searchfields) ? $this->searchFields : $searchfields;
        $relationSearch = is_null($relationSearch) ? $this->relationSearch : $relationSearch;
        $search = $this->request->get("search", '');
        $filter = $this->request->get("filter", '');
        $op = $this->request->get("op", '', 'trim');
        $sort = $this->request->get("sort", !empty($this->model) && $this->model->getPk() ? $this->model->getPk() : 'id');
        $order = $this->request->get("order", "DESC");
        $offset = $this->request->get("offset/d", 0);
        $limit = $this->request->get("limit/d", 999999);
        //新增自动计算页码
        $page = $limit ? intval($offset / $limit) + 1 : 1;
        if ($this->request->has("page")) {
            $page = $this->request->get("page/d", 1);
        }
        $this->request->get([config('paginate.var_page') => $page]);
        $filter = (array)json_decode($filter, true);
        
        if (isset($filter['have_uid'])) {
            $filter['have_uid'] = $filter['have_uid']-config('virtual_userid');
        }
        $op = (array)json_decode($op, true);
        $filter = $filter ? $filter : [];
        $where = [];
        $alias = [];
        $bind = [];
        $name = '';
        $aliasName = '';
        if (!empty($this->model) && $this->relationSearch) {
            $name = $this->model->getTable();
            $alias[$name] = Loader::parseName(basename(str_replace('\\', '/', get_class($this->model))));
            $aliasName = $alias[$name] . '.';
        }
        $sortArr = explode(',', $sort);
        foreach ($sortArr as $index => & $item) {
            $item = stripos($item, ".") === false ? $aliasName . trim($item) : $item;
        }
        unset($item);
        $sort = implode(',', $sortArr);
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $where[] = [$aliasName . $this->dataLimitField, 'in', $adminIds];
        }
        if ($search) {
            $searcharr = is_array($searchfields) ? $searchfields : explode(',', $searchfields);
            foreach ($searcharr as $k => &$v) {
                $v = stripos($v, ".") === false ? $aliasName . $v : $v;
            }
            unset($v);
            $where[] = [implode("|", $searcharr), "LIKE", "%{$search}%"];
        }
        $index = 0;
        foreach ($filter as $k => $v) {
            if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', $k)) {
                continue;
            }
            $sym = isset($op[$k]) ? $op[$k] : '=';
            if (stripos($k, ".") === false) {
                $k = $aliasName . $k;
            }
            $v = !is_array($v) ? trim($v) : $v;
            $sym = strtoupper(isset($op[$k]) ? $op[$k] : $sym);
            //null和空字符串特殊处理
            if (!is_array($v)) {
                if (in_array(strtoupper($v), ['NULL', 'NOT NULL'])) {
                    $sym = strtoupper($v);
                }
                if (in_array($v, ['""', "''"])) {
                    $v = '';
                    $sym = '=';
                }
            }

            switch ($sym) {
                case '=':
                case '<>':
                    $where[] = [$k, $sym, (string)$v];
                    break;
                case 'LIKE':
                case 'NOT LIKE':
                case 'LIKE %...%':
                case 'NOT LIKE %...%':
                    $where[] = [$k, trim(str_replace('%...%', '', $sym)), "%{$v}%"];
                    break;
                case '>':
                case '>=':
                case '<':
                case '<=':
                    $where[] = [$k, $sym, intval($v)];
                    break;
                case 'FINDIN':
                case 'FINDINSET':
                case 'FIND_IN_SET':
                    $v = is_array($v) ? $v : explode(',', str_replace(' ', ',', $v));
                    $findArr = array_values($v);
                    foreach ($findArr as $idx => $item) {
                        $bindName = "item_" . $index . "_" . $idx;
                        $bind[$bindName] = $item;
                        $where[] = "FIND_IN_SET(:{$bindName}, `" . str_replace('.', '`.`', $k) . "`)";
                    }
                    break;
                case 'IN':
                case 'IN(...)':
                case 'NOT IN':
                case 'NOT IN(...)':
                    $where[] = [$k, str_replace('(...)', '', $sym), is_array($v) ? $v : explode(',', $v)];
                    break;
                case 'BETWEEN':
                case 'NOT BETWEEN':
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr, function($v){
                        return $v != '' && $v !== false && $v !== null;
                    })) {
                        continue 2;
                    }
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'BETWEEN' ? '<=' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'BETWEEN' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $where[] = [$k, $sym, $arr];
                    break;
                case 'RANGE':
                case 'NOT RANGE':
                    $v = str_replace(' - ', ',', $v);
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr)) {
                        continue 2;
                    }
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'RANGE' ? '<=' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'RANGE' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $tableArr = explode('.', $k);
                    if (count($tableArr) > 1 && $tableArr[0] != $name && !in_array($tableArr[0], $alias) && !empty($this->model)) {
                        //修复关联模型下时间无法搜索的BUG
                        $relation = Loader::parseName($tableArr[0], 1, false);
                        $alias[$this->model->$relation()->getTable()] = $tableArr[0];
                    }
                    $where[] = [$k, str_replace('RANGE', 'BETWEEN', $sym) . ' TIME', $arr];
                    break;
                case 'NULL':
                case 'IS NULL':
                case 'NOT NULL':
                case 'IS NOT NULL':
                    $where[] = [$k, strtolower(str_replace('IS ', '', $sym))];
                    break;
                default:
                    break;
            }
            $index++;
        }
        if (!empty($this->model)) {
            $this->model->alias($alias);
        }
        $model = $this->model;
        $where = function ($query) use ($where, $alias, $bind, &$model) {
            if (!empty($model)) {
                $model->alias($alias);
                $model->bind($bind);
            }
            foreach ($where as $k => $v) {
                if (is_array($v)) {
                    call_user_func_array([$query, 'where'], $v);
                } else {
                    $query->where($v);
                }
            }
        };
        return [$where, $sort, $order, $offset, $limit, $page, $alias, $bind];
    }


    public function getLocation()
    {
        $config = get_addon_config('address');
        $maptype = $config['maptype'];
        if (!isset($config[$maptype . 'key']) || !$config[$maptype . 'key']) {
            $this->error("请在配置中配置对应类型地图的密钥");
        }
        $address = input('address','');
        $res = file_get_contents("https://apis.map.qq.com/ws/geocoder/v1/?address=".$address."&output=json&key=".$config[$maptype . 'key']);
        $decode = json_decode($res,1);
        if (isset($decode['status']) && $decode['status']==0) {
            // $res = gdEncrypt($decode['result']['location']['lng'],$decode['result']['location']['lat']);
            $this->success('','',['lng'=>$decode['result']['location']['lng'],'lat'=>$decode['result']['location']['lat']]);
        }
    }

    /**
     * 导入
     */
    public function import()
    {
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . 'public' . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, "w");
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding != 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }

        //加载文件
        $insert = [];
        $now_time = time();
        $date = date('Y-m-d H:i:s',$now_time);
        // 连接吃喝不愁数据库
        $db = Db::connect([
            'type'        => 'mysql',
            'dsn'         => '',
            'hostname'    => 'rr-uf64t31qat7k071at.mysql.rds.aliyuncs.com',
            'database'    => 'chbc',
            'username'    => 'chbc',
            'password'    => 'ChBuChOu$2023',
            'hostport'    => '3306',
            'params'      => [],
            'charset'     => 'utf8mb4',
            'prefix'      => 'chbc_',
        ]);
        $ossService = new \services\OssService();
        Db::startTrans();
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            $fields = [];
            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $fields[] = $val;
                }
            }
            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];
                $group_id = 0;
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $values[] = is_null($val) ? '' : $val;
                }
                // 店铺
                $shop = $db->name('shop')->where('id',$values[0])->find();
                if (!$shop) continue;
                $admin = $db->name('admin')->where('id',$shop['salesman_admin_id'])->find();
                $salesman_admin_id=0;
                if ($admin) {
                    $salesman_admin_id = Db::name('admin')->where('nickname',$admin['nickname'])->value('id');
                }
                $shop_no = $shop['shop_no'];
                $logo_pic = file_get_contents(config('chbc_upload_domain').$shop['logo_pic']);
                $dir = '/uploads/';    //生成的图片目录
                //图片路径
                $path = $dir . date("Ymd", time()) . '/';
                $imagePath = $path . md5($shop['id'].time() . mt_rand(1000, 9999)) . '.jpg';
                $savekey = trim($imagePath,'/');
                $file=$ossService->upload_file_content($logo_pic,$savekey);
                $shop['shop_no'] = $this->generateNo(['biz_tag'=>'shop_no','len'=>10,'int_prefix'=>1]);
                $shop['create_dt'] = $shop['update_dt'] = $date;
                $shop['create_by'] = 'excel';
                $shop['salesman_admin_id'] = $salesman_admin_id;
                $shop['logo_pic'] = $imagePath;
                unset($shop['id']);
                Db::name('shop')->insert($shop);
                $shop_follow = $db->name('shop_follow')->where('shop_no',$shop_no)->find();
                if ($shop_follow) {
                    unset($shop_follow['id']);
                    $shop_follow['shop_no'] = $shop['shop_no'];
                    $shop_follow['update_dt'] = $date;
                    Db::name('shop_follow')->insert($shop_follow);
                }
                $shop_platform = $db->name('shop_platform')->where('shop_no',$shop_no)->find();
                if ($shop_platform) {
                    unset($shop_platform['id']);
                    $shop_platform['shop_no'] = $shop['shop_no'];
                    $shop_platform['update_dt'] = $date;
                    $shop_platform['create_dt'] = $shop_platform['update_dt'] = $date;
                    if ($shop_platform['qrcode_pic']) {
                        $qrcode_pic = file_get_contents(config('chbc_upload_domain').$shop_platform['qrcode_pic']);
                        $dir = '/uploads/';    //生成的图片目录
                        //图片路径
                        $path = $dir . date("Ymd", time()) . '/';
                        $imagePath = $path . md5($shop['shop_no'].time() . mt_rand(1000, 9999)) . '.jpg';
                        $savekey = trim($imagePath,'/');
                        $file=$ossService->upload_file_content($qrcode_pic,$savekey);
                    }
                    $shop_platform['qrcode_pic'] = $imagePath;
                    Db::name('shop_platform')->insert($shop_platform);
                }
            }
            Db::commit();
        } catch (Exception $exception) {
            Db::rollback();
            $this->error($exception->getMessage());
        }

        $this->success();
    }

}
